<?php
class Search_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	/**
	 * 	BUSCADOR DE PELICULAS, SERIES Y ACTORES
	 * 
	 * 	@param array $params			Parametros Post enviados
	 * 
	 * 	@return Array
	 */
	public function search($params){
		$limit = isset($params['limit'])? $params['limit']: 10;
		$filter_text = $params['filter_text'];	
		$is_one = (count(explode(" ", $params['filter_text']))>1) ? FALSE : TRUE ;
		$str_match = ($is_one) ? '' : ", MATCH(titulo) AGAINST('$filter_text') AS coincidencia";
		
		$array = array();
		$this->db->
					select("titulo AS title, url_web, tabla, id_tabla".$str_match)->from('buscador');
					
						if($is_one){
							$this->db->like('titulo', $params['filter_text']);
							$this->db->order_by('titulo ASC');
						}
						else{
							$this->db->where("MATCH(titulo) AGAINST ('$filter_text')", NULL , FALSE);
							$this->db->order_by('coincidencia DESC');
						}
		$this->db->limit($limit);
		
		$res	= $this->db->get();
		foreach ($res->result_array() as $key => $value) {
			$value['image'] = $this->{'getImg_'.$value['tabla']}($value['id_tabla']);
			unset($value['id_tabla'], $value['tabla']);
			$array['result_search'][] = $value;
		}
		
		return array($array);
		
	}
	
	
	public function search2($params){	
		$is_one = (count(explode(" ", $params['q']))>1) ? FALSE : TRUE ;
		if($is_one){
			$sql = "titulo LIKE '%".$params['q']."%'";
			$order_by = 'titulo ASC';
			$coincidencia = '';
		}else{
			$sql = "MATCH(titulo) AGAINST ('".$params['q']."')";
			$order_by = 'coincidencia DESC';
			$coincidencia = ", MATCH(titulo) AGAINST('".$params['q']."') AS coincidencia";
		}
		
		if(isset($params['type'])){
			switch ($params['type']) {
				case 'p':
					$sql .= " AND (tabla = 'peliculas' OR tabla = 'posts')";
					//$field_hash = ($params['method'] === 'admin') ? ', pf.id_phash ' : '';
				break;
				case 's':
					$sql .= " AND (tabla = 'series_temporadas' OR tabla = 'series_capitulos' OR tabla = 'posts')";
					//$field_hash = ', pf.id_phash';
				break;
				case 'a':
					$sql .= " AND tabla = 'actores'";
				break;
			}
		}
		
		if(isset($params['id_usuario']) and isset($params['userFilm'])){
			$inner	= " AS b INNER JOIN peliculas_fuentes AS pf ON b.id_tabla = pf.id_pelicula AND b.tabla = 'peliculas'";
			$sql	.= " AND pf.id_usuario = ".$params['id_usuario']."";
		}
		else if(isset($params['id_usuario']) and isset($params['userSerie'])){
			$inner	= " AS b INNER JOIN series_capitulos_fuentes AS scf ON b.id_tabla = scf.id_capitulo AND b.tabla = 'series_capitulos'";
			$sql	.= " AND scf.id_usuario = ".$params['id_usuario']."";
		}
		else{$inner	= "";}
		
		$query = Sys::pagination("
			SELECT 
				tabla, id_tabla, titulo, url_web".$coincidencia."
			FROM buscador".$inner."
			WHERE ".$sql."
			ORDER BY ".$order_by, $params, TRUE);
		
		$response = array(
			'result_search' => array(), 
			'total_rows' 		=> $query['total_rows'],
			'items_per_page' 	=> $params['result_items_per_page'],
			'result_page' 		=> $params['result_page']
		);
		
		$res_list = $this->db->query($query['query']);
		$response['result_search'] = $res_list->result_array();
		
		return $response;
	}
	
	private function getImg_peliculas($id){
		$res = $this->db
			->select('url_poster_small')
			->from('peliculas')
			->where('id_pelicula = '.$id)
		->get();
		$res = $res->row();
		return $res->url_poster_small;
	}
	private function getImg_series_capitulos($id){
		$res = $this->db
			->select('st.url_poster_small')
			->from('series_temporadas AS st')
			->join('series_capitulos AS sc', 'st.id_temporada = sc.id_temporada', 'inner')
			->where('sc.id_capitulo = '.$id)
		->get();
		$res = $res->row();
		return $res->url_poster_small;
	}
	private function getImg_series_temporadas($id){
		$res = $this->db
			->select('url_poster_small')
			->from('series_temporadas')
			->where('id_temporada = '.$id)
		->get();
		$res = $res->row();
		return $res->url_poster_small;
	}
	private function getImg_actores($id){
		return Sys::$url_base.'application/images/anonimous44.jpg';
	}

	/**
	 * Regresa las pelicula y los links (servers) en las que el usuario a agregado link.
	 */
	public function getUserMisPeliculas($params){
		
		$is_one = (count(explode(" ", $params['q']))>1) ? FALSE : TRUE ;
		if($is_one){
			$sql = "b.titulo LIKE '%".$params['q']."%'";
			$order_by = 'b.titulo ASC';
			$coincidencia = '';
		}else{
			$sql = "MATCH(b.titulo) AGAINST ('".$params['q']."')";
			$order_by = 'coincidencia DESC';
			$coincidencia = ", MATCH(b.titulo) AGAINST('".$params['q']."') AS coincidencia";
		}

		$sql .= " AND (tabla = 'peliculas' OR tabla = 'posts')";
		if(isset($params['id_usuario']) and isset($params['userFilm'])){
			$inner	= " AS b INNER JOIN peliculas_fuentes AS pf ON b.id_tabla = pf.id_pelicula AND b.tabla = 'peliculas' INNER JOIN peliculas as p ON p.id_pelicula = b.id_tabla";
			$sql	.= " AND pf.id_usuario = ".$params['id_usuario']."";
		}

		$sql = "SELECT 
					p.id_pelicula, p.titulo".$coincidencia."
				FROM buscador".$inner."
				WHERE ".$sql."
				GROUP BY p.id_pelicula, p.titulo
				ORDER BY ".$order_by;
		
		$query 		= Sys::pagination($sql, $params, TRUE);
		$res_query 	= $this->db->query($query['query']);
		$response	= array(
							'result_search'		=> $res_query->result_array(),
							'total_rows' 		=> $query['total_rows'],
							'items_per_page' 	=> $params['result_items_per_page'],
							'result_page' 		=> $params['result_page']
						);

		if(count($response['result_search'])>0){
			foreach ($response['result_search'] as $key => $itm){
				$query = $this->db->query("SELECT pf.id_phash, s.nombre as servidor
										   FROM peliculas_fuentes as pf 
										   INNER JOIN servidores as s ON s.id_servidor = pf.id_servidor
										   WHERE id_pelicula = ".$itm['id_pelicula']);
						$response['result_search'][$key]['links'] = $query->result_array();
				}
		}
		// echo '<pre>';
		// var_dump($response['mispeliculas']);
		// echo '</pre>';exit;
		return $response;
		
	}

	/**
	 * Regresa las series|temporadas|episodios y los links (servers) en las que el usuario a agregado link.
	 */
	public function getUserMisSeries($params){

		// echo "SELECT 
		// 			s.id_serie, s.titulo, st.id_temporada, st.no_temporada, sc.id_capitulo, sc.no_capitulo, sc.titulo AS titulo_capitulo, scf.id_chash, srv.id_servidor, srv.nombre".$coincidencia."
		// 		FROM buscador".$inner."
		// 		WHERE ".$sql."
		// 		ORDER BY ".$order_by;exit;

	
		$like = ($params['q'] != '')?" AND s.titulo LIKE '%".$params['q']."%'":"";
		$sql = "SELECT s.id_serie, s.titulo
				FROM series AS s
				INNER JOIN series_temporadas AS st ON s.id_serie = st.id_serie
				INNER JOIN series_capitulos AS sc ON sc.id_temporada = st.id_temporada
				INNER JOIN series_capitulos_fuentes AS scf ON scf.id_capitulo = sc.id_capitulo
				WHERE scf.id_usuario = ".$params['id_usuario']."".$like."
				GROUP BY s.id_serie, s.titulo
				ORDER BY s.titulo";

		$query 		= Sys::pagination($sql, $params, TRUE);
		$res_query 	= $this->db->query($query['query']);
		$response	= array(
							'result_search'		=> $res_query->result_array(),
							'total_rows' 		=> $query['total_rows'],
							'items_per_page' 	=> $params['result_items_per_page'],
							'result_page' 		=> $params['result_page']
						);

		// echo '<pre>';
		// var_dump($response['result_search']);
		// echo '</pre>';exit;
		if(count($response['result_search'])>0){
			foreach ($response['result_search'] as $key => $serie){
				
				$temporadas = $this->db->query("SELECT st.id_temporada, st.no_temporada 
												 FROM series_temporadas as st
												 INNER JOIN series_capitulos AS sc ON sc.id_temporada = st.id_temporada
												 INNER JOIN series_capitulos_fuentes AS scf ON scf.id_capitulo = sc.id_capitulo
												 WHERE scf.id_usuario = ".$params['id_usuario']." AND st.id_serie = ".$serie['id_serie']."
												 GROUP BY st.id_temporada, st.no_temporada");

				$response['result_search'][$key]['temporadas'] = $temporadas->result_array();

				foreach ($response['result_search'][$key]['temporadas'] as $key2 => $temp){
				
					$capitulos = $this->db->query("SELECT sc.id_capitulo, sc.no_capitulo, sc.titulo 
													 FROM series_capitulos AS sc
													 INNER JOIN series_capitulos_fuentes AS scf ON scf.id_capitulo = sc.id_capitulo
													 WHERE scf.id_usuario = ".$params['id_usuario']." AND sc.id_temporada = ".$temp['id_temporada']."
													 GROUP BY sc.id_capitulo, sc.no_capitulo, sc.titulo");

					$response['result_search'][$key]['temporadas'][$key2]['capitulos'] = $capitulos->result_array();


					foreach ($response['result_search'][$key]['temporadas'][$key2]['capitulos'] as $key3 => $capitulo){
				
						$links = $this->db->query("SELECT scf.id_chash, scf.id_capitulo, srv.id_servidor, srv.nombre
														 FROM series_capitulos_fuentes AS scf
														 INNER JOIN servidores as srv ON srv.id_servidor = scf.id_servidor
														 WHERE scf.id_usuario = ".$params['id_usuario']." AND scf.id_capitulo = ".$capitulo['id_capitulo']);

						$response['result_search'][$key]['temporadas'][$key2]['capitulos'][$key3]['links'] = $links->result_array();
						
					}
					
				}

			}
		}
		// echo '<pre>';
		// var_dump($response['result_search']);
		// echo '</pre>';exit;
		return $response;
		
	}
}